/*
 * @Description:
 * @Author: 胡涛
 * @Date: 2023-06-06 09:20:37
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-12-18 20:14:04
 */
import configurationApi from "@/api/system/configuration";

import {
  PermissionDefinitionDto,
  SystemMenuDto,
  SystemUserDto,
} from "@/api/system/types";
import { clearAuthPermissions } from "@/helpers";
import { defineStore } from "pinia";
import { TOKEN_AUTH_TIME_KEY } from "@/helpers/loading"
import cookie from "@/helpers/cookie";

interface IAppState {
  token: string;
  sideMenuCollapse: boolean;
  currentUser: Partial<SystemUserDto>;
  grantedPolicies: Record<string, boolean>;
  allMenus: Array<Partial<SystemMenuDto>>;
  permissionDeninitions: Array<PermissionDefinitionDto>;
}

export const useAppStore = defineStore("app", {
  state: (): IAppState => {
    return {
      token: "",
      sideMenuCollapse: false,
      currentUser: {},
      grantedPolicies: {},
      allMenus: [],
      permissionDeninitions: [],
    };
  },
  actions: {
    /**
     * 设置token
     * @param token
     */
    setToken(token: string) {
      this.token = token;
      cookie.set(TOKEN_AUTH_TIME_KEY, new Date().getTime(), { "path": "/" });
    },
    /**
     *  设置显示菜单数据
     * @param isCollapse
     */
    setSideMenuCollapse(isCollapse: boolean) {
      this.sideMenuCollapse = isCollapse;
    },
    /**
     * 设置当前登录
     * @param user
     */
    setCurrentUser(user: Partial<SystemUserDto>) {
      this.currentUser = user;
    },

    /**
     * 设置权限数据
     * @param items
     */
    setGrantedPolicies(items: Record<string, boolean>) {
      this.grantedPolicies = items;
    },

    /**
     *
     * @param items
     */
    setAllMenus(items: Array<Partial<SystemMenuDto>>) {
      this.allMenus = items;
    },
    /**
     * 退出登录
     */
    logout() {
      this.allMenus = [];
      this.currentUser = {};
      this.token = "";
      this.permissionDefinitions = [];
      clearAuthPermissions()
    },
    async getPermissionDeninitions() {
      if (this.permissionDefinitions?.length) {
        return this.permissionDefinitions;
      }
      this.permissionDefinitions =
        await configurationApi.getPermissionDeninitions();
      return this.permissionDefinitions;
    },
  },
  persist: {
    enabled: true,
    strategies: [{ storage: localStorage, key: "vite-vue-store-app" }],
  },
});
